<?php

namespace App\Jobs;

use App\Models\Resume;
use App\Services\UploadService;
use App\Jobs\ResumeRecognitionJob;
use Illuminate\Support\Facades\Log;

class UploadResumeToOssJob extends Job
{
    // 任务超时时间（秒）
    public $timeout = 600;

    // 最大重试次数
    public $tries = 3;
    
    // 重试等待时间（秒）
    public $backoff = 60;

    // 指定队列名称
    public $queue = 'resume-upload';

    protected $resumeId;

    public function __construct(int $resumeId)
    {
        $this->resumeId = $resumeId;
    }

    private function uploadToOss(array $resume): string
    {
        if (empty($resume['file_path'])) {
            throw new \Exception('文件路径不能为空');
        }

        $filePath = storage_path('app/' . $resume['file_path']);
        $file = new \Illuminate\Http\UploadedFile(
            $filePath,
            basename($filePath)
        );

        $uploadService = app(UploadService::class);
        $result = $uploadService->uploadFile($file, 'resume');

        return $result['file_path'];
    }

    public function handle()
    {
        try {
            $resumeModel = app(Resume::class);
            $resume = $resumeModel->take(['id' => $this->resumeId], ['id', 'file_path']);
            if (empty($resume['file_path'])) {
                return;
            }

            $filePath = storage_path('app/' . $resume['file_path']);
            if (!file_exists($filePath)) {
                return;
            }

            // 上传简历至阿里云
            $ossFilePath = $this->uploadToOss($resume);
            $resumeModel->modify($this->resumeId, ['resume' => $ossFilePath]);

            // 加入处理简历队列
            dispatch(new ResumeRecognitionJob($this->resumeId));
        } catch (\Exception $e) {
            throw $e;
        }
    }
}